local UIBase = require("view.UIBase")
local TeamView = class("TeamView", UIBase)
local GameUtils = require("utils.GameUtils")
local Vector3 = require("utils.Vector3")
local UIUtil = require("utils.UIUtil")

function TeamView:ctor()
    local resource = {
        path = "Prefabs/View",
        name = "TeamView",
        canvas = 2 --1- fixcanvas 2-uicanvas 3-popcanvas
    }
    TeamView.super.ctor(self, resource)
end

function TeamView:awake()
end

function TeamView:start()
    self._signalUnSuccess =
        G_SignalManager:add(SignalConst.EVENT_HERO_UN_BATTLE_SUCCESS, handler(self, self._onEventUnBattleSuccess))
    self._signalChangeSuccess =
        G_SignalManager:add(SignalConst.EVENT_HERO_CHANGE_BATTLE_SUCCESS, handler(self, self._onEventChangeSuccess))

    self._btnClose.onClick:AddListener(handler(self, self._onCloseClick))
    for i = 1, 6 do
        self["_hero" .. i]:setCallback(
            function(state)
                self:_onClickAddHero(state, i)
            end
        )
    end
    self:_updateView()
end

function TeamView:_updateView()
    self._heros = G_UserData:getBattle():getBattleHeros()
    for i = 1, 6 do
        if self._heros[i] then
            self["_hero" .. i]:updateUI(self._heros[i])
        else
            self["_hero" .. i]:updateEmpty()
        end
    end
end

function TeamView:_onCloseClick()
    self:close()
end

function TeamView:_onClickAddHero(state, index)
    printDebug("TeamView:_onClickAddHero " .. index)
    if state == 1 then
        local pop = require("view.hero.PopupChooseHero").new(handler(self, self.onSelectedHero))
    else
        local train = require("view.hero.HeroTrainView").new(self._heros[index])
    end
end

function TeamView:onSelectedHero(heroId)
    if heroId == 0 then
        return
    end
    if G_UserData:getBattle():addHeroToBattle(heroId) then
        G_UIManager:showTip(Lang.get("lang_hero_battle_success"))
        self:_updateView()
    else
        G_UIManager:showTip(Lang.get("lang_hero_battle_fail"))
    end
end

function TeamView:onDestroy()
    self._signalUnSuccess:remove()
    self._signalUnSuccess = nil
    self._signalChangeSuccess:remove()
    self._signalChangeSuccess = nil
end

function TeamView:_onEventUnBattleSuccess(id, mess)
    self:_updateView()
end

function TeamView:_onEventChangeSuccess()
    self:_updateView()
end

return TeamView
